#!/bin/bash

# Copyright 2014 PerfKitBenchmarker Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -euo pipefail

HOOKS_DIR="$(dirname "$(test -L "$0" && echo "$(dirname $0)/$(readlink "$0")" || echo "$0")")"
OUT_FILE="${1:-/dev/stdout}"

# Set of modified files is those currently staged for commit (cached).
modified_files=($(git diff --cached --name-only --diff-filter ACM))

# The checker script has a nonzero exit code on errors and reports
# problems on STDOUT, with informational messages on STDERR. Append
# errors to the commit message with leading comment markers added, and
# return success so that we don't block the message. Return failure
# only in case of unexpected errors.

if [[ "${#modified_files[@]}" -ne 0 ]]; then
  (
    if ! PREPARE_COMMIT_HOOK="true" "${HOOKS_DIR}/check" "${modified_files[@]}"; then
      echo >&2 "Error: unexpected error in prepare-commit-msg hook. Commit aborted."
      exit 1
    fi
  ) | sed 's/^/# /' >>"$OUT_FILE"
fi
